//
//  TSCMyAlertView.m
//  Tsc_IOS
//
//  Created by Rio on 15-5-18.
//  Copyright (c) 2015年 idream. All rights reserved.
//
// == 实现思路
// 1. 自身就是一个垂直方向上的LinearLayout。没有c2c、c2f的padding
// 2. 自身的直接子view，就是UIView，一行一个row
// 3. 所有其他UI元素（标题、按钮等），都放在直接子view中row。这些UI元素与row之间的padding，来控制整体的padding
//
// == 注意：
// 1. 第一次实现的时候，发现一个奇怪的现象：如果不将MyDialog声明为UIView，而声明为NSObject，gestureBG和dialog都作为其类属性存在，则将导致gestureBG点击时，无法找到写在MyDialog中的@selector。查阅相关资料，可能是这种方法将导致MyDialog对象被提前回收，所以其@selector也就没有了。所以目前还得采取旧办法：将MyDialog声明为UIView，再将gestureBG和dialog添加到其中
//
// == TODO
// 1.
// xx 2. TODO 通过代码动态修改各属性时，将无法动态刷新界面

#define DIALOG_W 280 // dialog的宽度
#define ELEMENT_HEIGHT 50.0f // 每一个UI元素的高度
#define PROCESSING_INDICATOR_WH 50.0f // 进度指示器的宽高
#define PROCESSING_INDICATOR_PADDING 5
#define HLSH 1 // Horizontal Line Seperator Height
#define VLSW 1 // Vertical Line Seperator Witdh
#define APPEAR_DISAPPEAR_TI 0.2 // 动画淡入、淡出的时间

#import "TSCMyDialog.h"
#import "TSCMyUtil.h"
#import "TSCConstants.h"
#import "TSCMyUIUtil.h"
#import "TSCLinearLayout.h"
#import "TSCMyClickBtn.h"
#import "TSCMyUtil.h"


@implementation TSCMyDialog {
    UIViewController * _viewController; // 当前要添加到的vc
    UIView * _gestureBG; // 背景图层，用来接收用户点击事件，从而关闭dialog
}


#pragma mark 初始化

- (id)init {
    // 以满屏创建
    self  = [super init];
    if (self) {
        [self initMyDialog];
    }
    return self;
}

//- (id)initWithViewController:(UIViewController *)vc {
//    // 初始化（以全屏创建）
//    self = [self init];
//    
//    // 初始化属性
//    _viewController = vc;
//    
//    return self;
//}

- (void) initMyDialog {
    // 设置各属性
    _viewController = [TSCMyUtil getCurrentViewController]; // 注：获得当前vc
    
    _textSize = [TSCMyUIUtil getSystemDefaultFont].pointSize;
    _titleText = @"";
    _processingMsgText = @"";
    _msgText = @"";
    _customView = nil;
    _leftBtnText = @"";
    _middleBtnText = @"";
    _rightBtnText = @"";
    
    _leftBtnOnClickListener = nil;
    _middleBtnOnClickListener = nil;
    _rightBtnOnClickListener = nil;
    
    _isShowing = NO;
}

#pragma mark 私有方法

/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect
 {
 // Drawing code
 }
 */

/* private */ - (void) layoutUI {
    
    // 先将自身添加到当前界面中（因为后续要设置约束）
    // 方式一：加入全局窗体。特点：当前vc消失后，dialog依然在
    //    [[[UIApplication sharedApplication].delegate window]addSubview:self];
    // 方式二：加入当前窗体。特点：当前vc消失后，dialog也不在了
    [_viewController.view addSubview:self];
    
    // 添加modal背景
    _gestureBG = [[UIView alloc]init];
    [_gestureBG setBackgroundColor:COLOR_MT_DIALOG_MODAL];
    [self addSubview:_gestureBG];
    
    // modal注册事件
    _gestureBG.userInteractionEnabled = YES;
    UITapGestureRecognizer * tgrModalBGClicked = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(modalBGClicked)];
    [_gestureBG addGestureRecognizer:tgrModalBGClicked];
    
    // 创建dialog（创建各UI元素、设置各UI元素事件、将dialog加入self、添加dialog约束等...）
    _dialog = [self createAndAddDialogWithMyDialog:self];
    
    // 添加约束
    // self
    self.translatesAutoresizingMaskIntoConstraints = NO;
    [NSLayoutConstraint activateConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[self]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(self)]];
    [NSLayoutConstraint activateConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[self]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(self)]];
    // bg
    _gestureBG.translatesAutoresizingMaskIntoConstraints = NO;
    [NSLayoutConstraint activateConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_gestureBG]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_gestureBG)]];
    [NSLayoutConstraint activateConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[_gestureBG]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_gestureBG)]];
    // dialog
    // 注：dialog的约束在createDialogWithMyDialog()中已经设置了
    
}

// 创建各UI元素、设置各UI元素事件、将dialog加入self、添加dialog约束等...
// 注：因为有可能用另一个MyDialog B来替换正在显示的MyDialog A的内容，所以抽象此方法
/* private */ - (TSCLinearLayout *) createAndAddDialogWithMyDialog: (TSCMyDialog *) md {
    // 声明局部变量
    UIFont * systemFont = [TSCMyUIUtil getSystemDefaultFont];
    
    BOOL hasTitle = ![TSCMyUtil isStringEmpty:md.titleText];
    BOOL hasProcessing = ![TSCMyUtil isStringEmpty:md.processingMsgText];
    BOOL hasMessage = ![TSCMyUtil isStringEmpty:md.msgText];
    BOOL hasCustomView = md.customView == nil ? NO : YES;
    BOOL hasLeftBtn = ![TSCMyUtil isStringEmpty:md.leftBtnText];
    BOOL hasMiddleBtn = ![TSCMyUtil isStringEmpty:md.middleBtnText];
    BOOL hasRightBtn = ![TSCMyUtil isStringEmpty:md.rightBtnText];
    
    
    // 设置dialog
    TSCLinearLayout * dialog = [[TSCLinearLayout alloc]init];
    dialog.orientation = LINEAR_LAYOUT_ORIENTATION_VERTICAL;
    dialog.distribution = LINEAR_LAYOUT_DISTRIBUTION_NONE;
    dialog.backgroundColor = COLOR_MT_DIALOG_BG;
    [TSCMyUIUtil setUIRoundRectBG:dialog radius:10.0]; // dialog圆角
    [self addSubview:dialog]; // TODO 需要先将dialog隐藏吗？
    
    // 添加约束
    // dialog
    dialog.translatesAutoresizingMaskIntoConstraints = NO;
    [NSLayoutConstraint constraintWithItem:dialog attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterX multiplier:1.0f constant:0.0f].active = YES;
    [NSLayoutConstraint constraintWithItem:dialog attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterY multiplier:1.0f constant:0.0f].active = YES;
    [NSLayoutConstraint constraintWithItem:dialog attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeWidth multiplier:(2.0f / 3.0f) constant:0.0f].active = YES;
    // 注：高度由直接子view的高度决定
    
    // ===== 1 从上至下向dialog中添加UI元素
    
    // 设置title
    if(hasTitle) {
        UILabel * lbTitle = [[UILabel alloc]init];
        lbTitle.frame = CGRectMake(0, 0, 0, 50); // 仅指定高度，宽度占满父元素
        lbTitle.font = [systemFont fontWithSize:_textSize];
        lbTitle.text = md.titleText;
        lbTitle.textAlignment = NSTextAlignmentCenter;
        [dialog addSubview:lbTitle];
        
        // hls1
        if (
            hasProcessing
            ||
            hasMessage
            ||
            hasCustomView
            ||
            hasLeftBtn
            ||
            hasMiddleBtn
            ||
            hasRightBtn
            ) {
            UIView * hls1 = [self createHLS];
            [dialog addSubview:hls1];
        }
    }
    
    // 设置进度标识及进度说明文字
    if (hasProcessing) {
        UIView * viProcessingPanel = [[UIView alloc]init];
        viProcessingPanel.frame = CGRectMake(0, 0, 0, ELEMENT_HEIGHT); // 仅指定高度，宽度占满父元素
        [dialog addSubview:viProcessingPanel];
        
        // 设置进度标识
        UIActivityIndicatorView * aivProcessing = [[UIActivityIndicatorView alloc]init];
        aivProcessing.color = COLOR_MT;
        [aivProcessing startAnimating];
        [viProcessingPanel addSubview:aivProcessing];
        
        // 设置进度说明文字
        UILabel * lbProcessing = [[UILabel alloc]init];
        lbProcessing.font = [systemFont fontWithSize:_textSize];
        lbProcessing.text = md.processingMsgText;
        [viProcessingPanel addSubview:lbProcessing];
        
        // 添加约束
        // 注：要将约束添加在processingPanel上，而不是vc.view上
        // aiv
        aivProcessing.translatesAutoresizingMaskIntoConstraints = NO;
        [NSLayoutConstraint activateConstraints:[NSLayoutConstraint constraintsWithVisualFormat:[NSString stringWithFormat:@"H:|[aivProcessing(%f)][lbProcessing]|", PROCESSING_INDICATOR_WH] options:0 metrics:nil views:NSDictionaryOfVariableBindings(aivProcessing, lbProcessing)]];
        [NSLayoutConstraint activateConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[aivProcessing]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(aivProcessing)]];
        // lbProcessing
        lbProcessing.translatesAutoresizingMaskIntoConstraints = NO;
        [NSLayoutConstraint activateConstraints:[NSLayoutConstraint constraintsWithVisualFormat:[NSString stringWithFormat:@"V:|[lbProcessing]|"] options:0 metrics:nil views:NSDictionaryOfVariableBindings(lbProcessing)]];
        
        // hls2
        if (
            hasMessage
            ||
            hasLeftBtn
            ||
            hasMiddleBtn
            ||
            hasRightBtn
            ) {
            UIView * hls2 = [self createHLS];
            [dialog addSubview:hls2];
        }
    }
    
    // 设置message
    if(hasMessage) {
        UILabel * lbMsg = [[UILabel alloc]init];
        lbMsg.frame = CGRectMake(0, 0, 0, ELEMENT_HEIGHT); // 仅指定高度，宽度占满父元素
        lbMsg.font = [systemFont fontWithSize:_textSize];
        lbMsg.text = md.msgText;
        lbMsg.textAlignment = NSTextAlignmentCenter;
        [dialog addSubview:lbMsg];
        
        // hls3
        if (
            hasCustomView
            ||
            hasLeftBtn
            ||
            hasMiddleBtn
            ||
            hasRightBtn
            ) {
            UIView * hls3 = [self createHLS];
            [dialog addSubview:hls3];
        }
    }
    
    // 设置customView
    if (hasCustomView) {
        // 重置customerView的宽高
        // 重置原则：
        // 1. width：重置为0，以自适应dialog宽度；
        // 2. height：忽略，不重置。
        //   2.1 如果customerView自身有height，则将height作为customView的高度约束添加到dialog
        //   2.2 或者customerView自身没有设置height，则可能customView是一个LinearLayout（比如GCSelector），通过直接子view设置自身height，不用重置
        CGFloat cvX = md.customView.frame.origin.x;
        CGFloat cvY = md.customView.frame.origin.y;
        CGFloat cvW = md.customView.frame.size.width;
        CGFloat cvH = md.customView.frame.size.height;
        if (cvW != 0) {
            NSLog(@"[W]%s: customView的width建议设置为0（当前值：%f），以自适应dialog宽度。将对width进行重置...", __FUNCTION__, cvW);
            cvW = 0;
        }
        md.customView.frame = CGRectMake(cvX, cvY, cvW, cvH);
        
        [dialog addSubview:md.customView];
        
        // hls4
        if (
            hasLeftBtn
            ||
            hasMiddleBtn
            ||
            hasRightBtn
            ) {
            UIView * hls4 = [self createHLS];
            [dialog addSubview:hls4];
        }
    }
    
    // ===== 2. 从左至右绘制UI元素
    
    if (hasLeftBtn || hasMiddleBtn || hasRightBtn) {
        // 创建按钮面板
        TSCLinearLayout * llBtnPanel = [[TSCLinearLayout alloc]init];
        llBtnPanel.frame = CGRectMake(0, 0, 0, ELEMENT_HEIGHT); // 仅指定高度，宽度占满父元素
        llBtnPanel.orientation = LINEAR_LAYOUT_ORIENTATION_HORIZONTAL;
        llBtnPanel.distribution = LINEAR_LAYOUT_DISTRIBUTION_FILL_EQUALLY;
        [dialog addSubview:llBtnPanel];
        
        // 左按钮
        if (hasLeftBtn) {
            TSCMyClickBtn * btnLeft = [TSCMyClickBtn buttonWithType:UIButtonTypeSystem];
            btnLeft.titleLabel.font = [systemFont fontWithSize:_textSize];
            [btnLeft setTitle:md.leftBtnText forState:UIControlStateNormal];
            [llBtnPanel addSubview:btnLeft];
            
            // 注册事件
            btnLeft.btnClickedListener = ^(TSCMyClickBtn * btn) {
                if (md.leftBtnOnClickListener) {
                    md.leftBtnOnClickListener(btn, md);
                }
            };
        }
        // vls1
        if (hasLeftBtn && (hasMiddleBtn || hasRightBtn)) {
            UIView * vls1 = [self createVLS];
            [llBtnPanel addSubview:vls1];
        }
        
        // 中按钮
        if(hasMiddleBtn) {
            TSCMyClickBtn * btnMiddle = [TSCMyClickBtn buttonWithType:UIButtonTypeSystem];
            btnMiddle.titleLabel.font = [systemFont fontWithSize:_textSize];
            [btnMiddle setTitle:md.middleBtnText forState:UIControlStateNormal];
            [llBtnPanel addSubview:btnMiddle];
            
            // 注册事件
            btnMiddle.btnClickedListener = ^(TSCMyClickBtn * btn) {
                if (md.middleBtnOnClickListener) {
                    md.middleBtnOnClickListener(btn, md);
                }
            };
        }
        
        // vls2
        if (hasMiddleBtn && hasRightBtn) {
            UIView * vls2 = [self createVLS];
            [llBtnPanel addSubview:vls2];
        }
        
        // 右按钮
        if(hasRightBtn) {
            TSCMyClickBtn * btnRight = [TSCMyClickBtn buttonWithType:UIButtonTypeSystem];
            btnRight.titleLabel.font = [systemFont fontWithSize:_textSize];
            [btnRight setTitle:md.rightBtnText forState:UIControlStateNormal];
            [llBtnPanel addSubview:btnRight];
            
            // 注册事件
            btnRight.btnClickedListener = ^(TSCMyClickBtn * btn) {
                if (md.rightBtnOnClickListener) {
                    md.rightBtnOnClickListener(btn, md);
                }
            };
        }
    }
    
    return dialog;
}


/* private */ - (UIView *) createHLS {
    UIView * seperator = [[UIView alloc]init];
    seperator.frame = CGRectMake(0, 0, 0, 1); // 仅指定高度，因为宽度会因为添加到LinearLayout中而自动与父view等宽
    seperator.backgroundColor = COLOR_MT;
    return seperator;
}

/* private */ - (UIView *) createVLS {
    UIView * seperator = [[UIView alloc]init];
    seperator.frame = CGRectMake(0, 0, 1, 0); // 仅指定宽度，因为高度会因为添加到LinearLayout中而自动与父view等高
    seperator.backgroundColor = COLOR_MT;
    return seperator;
}

/* private */ - (void) modalBGClicked {
    // 点击背景时自动关闭
    [self dismiss];
}

#pragma mark 公有方法

- (void) show {
    // 先检查是否设置了vc，因为外部使用者有可能直接使用init()来初始化，从而忘记设置vc
    NSAssert(_viewController != nil, @"[E]%s: MyDialog调用show()方法时，viewController为nil！请先设置viewController！", __FUNCTION__);
    
    // 先设置透明
    self.alpha = 0.0f;
    
    // 界面布局
    [self layoutUI];
    
    // 动画显示
    [UIView animateWithDuration:0.5 animations:^{
        self.alpha = 1.0f;
        _isShowing = YES;
    }];
}

- (void) dismiss {
    // 动画显示
    [UIView animateWithDuration:0.5 animations:^{
        self.alpha = 0.0f;
    } completion:^(BOOL finished) {
        // 将所有子view移除，否则将导致每一次show()调用时，加入self的子view会越来越多
        [TSCMyUIUtil removeAllSubviews:self];
        
        // 从主窗体中移除
        [self removeFromSuperview];
        _isShowing = NO;
    }];
}

- (void) replaceContentViewWithOtherDialog:(TSCMyDialog *)otherDialog {
    // 删除旧的dialog
    [_dialog removeFromSuperview];
    
    // 创建并显示新的dialog
    _dialog = [self createAndAddDialogWithMyDialog:otherDialog];
    
    
//    // 删除每一个旧子view
//    for (UIView * subView in [_dialog subviews]) {
//        [subView removeFromSuperview];
//    }
//    
//    // 将新dialog整体作为子view添加进来。这样做的效果是：如果多次调用此方法，则dialog的外层会不断嵌套UIView
//    [_dialog addSubview:otherDialog.dialog];
    
    // 注：不能这样写，是因为子view被添加到新的父view后，原来的事件（target）接收者已经不在了（原来的接收者是旧父view，可能被系统回收了），而新的接收者还没有被子view注册。除非手工遍历每一个子view，重新将它们的事件注册在新父view上
    //    // 添加所有新子view
    //    for (UIView * subView in [otherDialog subviews]) {
    //        [self addSubview:subView];
    //    }
    
}



@end
